<template>
  <div class="taskHandle box">
    <basic-container>
      <el-form ref="add-form" :model="form" :rules="rules">
        <h3>预算申请信息</h3>
        <el-divider></el-divider>
        <table class="customTable" align="center">
          <tr>
            <th width="350">预算编号：</th>
            <th width="400">{{form.applyData.budgetCode}}</th>
            <th width="350">申请名称：</th>
            <th width="400">{{form.applyData.applyName}}</th>
          </tr>

          <tr>
            <th width="350">申请部门：</th>
            <th width="400">{{applyDept2}}</th>
            <th width="350">申请类型：</th>
            <th width="400">{{applyType2}}</th>
          </tr>

          <!-- <tr>
            <th colspan="4">
              <el-form-item label="原预算额(元)" prop="applyData.budgetSum">
                <el-input
                  v-model="form.applyData.budgetSum"
                  readonly="readonly"
                  placeholder="原预算额(元)"
                />
              </el-form-item>
            </th>
          </tr>

          <tr>
            <th colspan="4">
              <el-form-item label="调整后预算额(元)" prop="applyData.budgetSum2">
                <el-input v-model="form.applyData.budgetSum2" placeholder="调整后预算额(元)" />
              </el-form-item>
            </th>
          </tr>

          <tr>
            <th colspan="4">
              <el-form-item label="预算变化(元)" prop="applyData.changeAmount">
                <el-input v-model="form.applyData.changeAmount" placeholder="预算变化(元)" />
              </el-form-item>
            </th>
          </tr>-->

          <tr>
            <th colspan="4">
              <el-form-item label="费用说明" prop="applyData.remarks">
                <el-input v-model="form.applyData.remarks" placeholder="请输入费用说明" />
              </el-form-item>
            </th>
          </tr>
        </table>

        <el-table
          :data="form.itemValueList"
          class="dubgetTable"
          row-key="itemId"
          default-expand-all
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        >
          <el-table-column class="weight" header-align="center" prop="itemName" label="科目" width="300">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{ scope.row.itemName }}</span>
              <el-switch
                v-model="scope.row.isNead"
                v-if="scope.row.children == null"
                :width="28"
                active-value="1"
                inactive-value="0"
                @change="handleIsNeadChange($event, scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column align="center" label="原金额(元)">
            <el-table-column align="center" prop="itemValue" :label="`${form.applyData.budgetSum}`" />
          </el-table-column>
          <el-table-column align="center" label="调整后金额(元)">
            <el-table-column align="center" prop="itemValuePre" :label="`${form.applyData.budgetSum2 || '暂无数据'}`">
              <template slot-scope="scope">
                <el-input
                  clearable
                  maxlength="15"
                  @change="budgetChange"
                  v-only-number="{min:0,precision:2}"
                  :disabled="scope.row.children !== null || scope.row.isNead == 0"
                  v-model="scope.row.itemValuePre"
                />
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column align="center" label="变化金额(元)">
            <el-table-column align="center" prop="itemValue" :label="`${form.applyData.changeAmount || '暂无数据'}`">
              <template slot-scope="scope">{{`${scope.row.changeAmount>0 ? '+':''}${scope.row.changeAmount || 0}`}}</template>
            </el-table-column>
          </el-table-column>
        </el-table>

        <!-- <h3>预算科目</h3>
        <el-divider></el-divider>
        <el-table :data="this.form.itemValueList" class="flowTable"  stripe>
          <el-table-column label="科目名称" prop="itemName">
            <template slot-scope="scope">
              <el-input v-model="scope.row.itemName" readonly="readonly"></el-input>
            </template>
          </el-table-column>

          <el-table-column label="原金额(元)" prop="itemValue">
            <template slot-scope="scope">
              <el-input v-model="scope.row.itemValue"></el-input>
            </template>
          </el-table-column>

          <el-table-column label="调整后金额(元)" prop="itemValuePre">
            <template slot-scope="scope">
              <el-input v-model="scope.row.itemValuePre"></el-input>
            </template>
          </el-table-column>

          <el-table-column label="变化金额(元)" prop="changeAmount">
            <template slot-scope="scope">
              <el-input v-model="scope.row.changeAmount"></el-input>
            </template>
          </el-table-column>
        </el-table>-->
      </el-form>

      <!--      <h3>文件上传</h3>-->
      <!--      <el-divider></el-divider>-->
      <!--      <div>-->
      <!--        <upload-media-->
      <!--          type="file"-->
      <!--          ref="myApply"-->
      <!--          :url="fileUploadUrl"-->
      <!--          :busId="busId"-->
      <!--          :modelType="modelType"-->
      <!--          @onSuccess="onSuccess"-->
      <!--          @onError="onError"-->
      <!--          @beforeUpload="beforeUpload"-->
      <!--          @handleClean="handleClean"-->
      <!--          :propsFileList="uploadFileList"-->
      <!--          :isShowFileList="true"-->
      <!--          :isView="false"-->
      <!--        ></upload-media>-->
      <!--      </div>-->
      <fileUpload ref="fileUpload" type="edit" :busId="fileId" :fileId="fileId2" v-if="showUpload" @onSuccess="handleCompleted" />

      <h3>流程记录</h3>
      <el-divider></el-divider>
      <el-table :data="busifoData" class="flowTable" stripe>
        <el-table-column label="序号" type="index" width="75" align="center" />
        <el-table-column label="业务类型" prop="busiType" align="center" />
        <el-table-column label="办理环节" prop="taskName" align="center" />
        <el-table-column label="办理结果" prop="operResult" align="center">
          <template slot-scope="scope">
            <span v-for="(item,index) in operlts" :key="index" v-if="scope.row.operResult==item.id">{{item.value}}</span>
          </template>
        </el-table-column>
        <el-table-column label="办理意见" prop="operIdea" align="center" />
        <el-table-column label="经办人" prop="operPerson" align="center" />
        <el-table-column label="经办时间" prop="operaTime" align="center" />
      </el-table>

      <h3>业务办理</h3>
      <el-divider />
      <table class="customTable" :table-loading="tableLoading">
        <tr>
          <th class="label" align="right">
            <font>*</font>办理结果：
          </th>
          <td colspan="5">
            <el-radio-group v-model="radios" @change="onBljg()">
              <el-radio v-for="(iteam,index) in operResults" :key="index" :label="index">{{iteam.resultName}}</el-radio>
            </el-radio-group>
          </td>
        </tr>
        <tr>
          <td class="label" align="right">
            <font>*</font>办理意见：
          </td>
          <td colspan="5">
            <el-input type="textarea" placeholder="请输入内容" v-model="texts"></el-input>
          </td>
          <!--  <th><el-button type="primary" @click="Opinions()">常用意见</el-button></th>-->
        </tr>
        <tr>
          <td class="label" align="right">
            <font>*</font>办理时间：
          </td>
          <td>
            <el-input readonly v-model="datatime" />
          </td>
          <td class="label" align="center">
            <font>*</font>办理人：
          </td>
          <td>{{user.realName}}</td>
          <td class="label" align="center">
            <font>*</font>下一环节经办人：
          </td>
          <td>
            <el-input readonly v-model="nextResultName" />
          </td>
        </tr>
      </table>
      <div class="operaList">
        <el-button type="warning" :disabled="this.status == 0" @click="release()">释放任务</el-button>
        <el-button type="success" :disabled="this.status == 0" @click="uploadDeployInfo()">查看流程图</el-button>
        <el-button type="primary" :disabled="this.status == 0" v-throttle="[save]">提交</el-button>
        <el-button @click="returns()">返回</el-button>
      </div>
      <flow-chart ref="flowChart"></flow-chart>
      <history-routes ref="historyRoutes" style="display: none"></history-routes>
      <!--<busimain-opinions ref="busimainOpinions"></busimain-opinions>-->
    </basic-container>
  </div>
</template>

<script>
// import busimainOpinions from './busimain-opinions'
import axios from "axios";
import flowChart from "./flow-chart";
import dbl from "@/utils/dbl";
import historyRoutes from "@/layout/history-routes";
import { getDict } from "~/utils";
import uploadMedia from "@/components/upload-media";
import { getBudgetApply, getItem, getItem2, putObj, putObj2, putObj3 } from "@/views/wy-budget/api/budgetapply.js";
import { getFiles, checkFiles, delFiles } from "@/views/wy-budget/api/fileoperation.js";
import { saveBudgetFlow } from "@/views/wy-budget/api/budgetflow.js";
import Budget from '@/assets/vue-mixin/budget'
import { mapState } from "vuex";
import fileUpload from '@/views/wy-budget/components/fileUpload'
import { formatMoney } from '@/utils'

export default {
  name: "business-handle",
  mixins: [Budget],
  components: { flowChart, historyRoutes, uploadMedia, fileUpload },
  data () {
    var doubleValidate = (rule, value, callback) => {
      let reg = /(^(([1-9]+\d*)|(0{1}))(.\d{1,2})?)|(^-([1-9]+\d*(\.\d{1,2})?|0\.(0[1-9]{1}|[1-9]{1}\d?)))/;
      let lable = rule.message;
      if (!reg.test(value)) {
        return callback(new Error("数值格式错误"));
      } else {
        callback();
      }
    };

    return {
      radios: 0, // 办理结果选择
      texts: "",
      tableLoading: false,
      datatime: formatTimeToStr(new Date().getTime()), // 当前时间
      busiIds: [],
      busifoData: [], //流转记录
      operResults: [], // 办理结果
      operlts: [
        {
          //  流转记录
          id: "0",
          value: "不通过",
        },
        {
          id: "1",
          value: "通过",
        },
        {
          id: "9",
          value: "返回受理",
        },
      ],
      nextResultName: "", // 下一个经办人
      UserId: "",
      status: 1,

      showUpload: false,
      fileId: '',
      fileId2: '',
      isShow: false,
      fileUploadUrl: "/admin/sys-file/upLodeFileEdit",
      uploadFileList: [],
      fileList: [],
      modelType: "budgetApply",
      isEdit: true,
      busId: "",

      budgetFlow: {
        applyId: "",
        busiId: "",
        procInstId: "",
        applyDept: "",
      },

      form: {
        applyData: {
          applyId: "",
          busiId: "",
          budgetId: "",
          budgetCode: "",
          applyName: "",
          applyDept: "",
          applyType: "",
          budgetSum: "",
          remarks: "",
          fileId: "",
        },
        itemValueList: [],
        operateType: "",
      },

      rules: {
        applyData: {
          budgetSum: [
            {
              required: true,
              message: "请输入预算总金额",
              trigger: "blur",
            },
            {
              validator: doubleValidate,
              trigger: "blur",
            },
          ],
          budgetSum2: [
            {
              required: true,
              message: "调整后金额不能为空",
              trigger: "blur",
            },
            {
              validator: doubleValidate,
              trigger: "blur",
            },
          ],
          changeAmount: [
            {
              required: true,
              message: "变化金额不能为空",
              trigger: "blur",
            },
            {
              validator: doubleValidate,
              trigger: "blur",
            },
          ],
          remarks: [
            {
              required: true,
              message: "请输入费用说明",
              trigger: "blur",
            },
            {
              min: 0,
              max: 100,
              message: "长度在 0 到 100 个字符",
              trigger: "blur",
            },
          ],
        },
      },
    };
  },

  computed: {
    ...mapState({ user: (state) => state.user.user }),

    applyDept2: function () {
      let types = getDict("budget_department");
      let pv = this.form.applyData.applyDept;
      if (pv && types.length > 0) {
        const pts = types.filter((t) => t.value == pv);
        return pts ? pts[0].label : "";
      }
      return "";
    },

    applyType2: function () {
      let types = getDict("budget_type");
      let pv = this.form.applyData.applyType;
      if (pv && types.length > 0) {
        const pts = types.filter((t) => t.value == pv);
        return pts ? pts[0].label : "";
      }
      return "";
    },
  },

  mounted () {
    this.init();
  },
  methods: {
    init () {
      this.busiIds = this.$route.query.busiIds;
      this.getList(this.busiIds.busiId);
    },

    uploadDeployInfo () {
      this.$refs.flowChart.show(this.busiIds);
    },
    sendFormData (val) {
      this.$loading({
        lock: true,
        text: "数据处理中",
      });
      if (val && this.isEdit) {
        //this.form.applyData.fileId2 = val;
        this.busId = val;
        this.isEdit = true;
      }
      this.form.applyData.isEdit = '1'
      putObj3(this.form)
        .then((rep) => {
          this.flowSubmit()
        })
        .catch((e) => {
          this.errormessage("保存失败");
        }).finally(() => {
          this.$loading.close();
        });
    },
    flowSubmit () {
      const config = {
        headers: { Authorization: dbl.get("token") },
      };

      const loading = this.$loading({
        lock: true,
        text: "数据处理中",
      });

      axios
        .post(
          "/api/flowbusimain/doSubmit",
          {
            busiId: this.busiIds.busiId,
            busiTaskCode: this.busiIds.busiTaskCode,
            operIdea: this.texts,
            operResult: this.operResults[this.radios].resultCode,
            userId: this.UserId,
          },
          config
        )
        .then((response) => {
          if (response.data.msg == "提交成功。") {
            this.$message.success(response.data.msg);
            // 获取办理 流程
            axios
              .get(
                "/api/flowbusimain/getOperProcList/" +
                this.busiIds.busiId,
                config
              )
              .then((response) => {
                this.busifoData = response.data.data;

                getBudgetApply(this.busiIds.busiId).then(respData => {
                  this.budgetApply = respData.data.data
                  this.budgetApply.checkStatus = '101';
                  this.budgetApply.isEdit = '1';

                  putObj(this.budgetApply).then(respData => {
                  }).catch(e => {
                  })

                  this.budgetFlow.applyId = this.budgetApply.applyId
                  this.budgetFlow.busiId = this.busiIds.busiId
                  this.budgetFlow.procInstId = this.busiIds.procInstId
                  this.budgetFlow.applyDept = this.budgetApply.applyDept


                  saveBudgetFlow(this.budgetFlow).then(respData => {
                  }).catch(e => {
                  })
                }).catch(e => {

                })
              })
              .catch((e) => { });

            loading.close();
            this.status = 0;
          } else {
            this.$message.error(response.data.msg);
            loading.close();
          }
          this.release(1);
        })
        .catch((e) => {

          loading.close();
        });
    },
    save () {
      this.form.operateType = "4";
      // ==================
      this.checkWillBe() && this.$refs["add-form"].validate((valid) => {
        if (valid) {
          this.$refs.fileUpload.submit();
        } else {
          return;
        }
      });

      // ===================
    },
    release (data) {
      // 释放任务
      const config = {
        headers: { Authorization: dbl.get("token") },
      };
      axios
        .get("/api/flowbusimain/doTaskUnLock/" + this.busiIds.busiId, config)
        .then((response) => {
          if (data == null) {
            if (response.data.msg == "释放任务成功。") {
              this.$message.success(response.data.msg);
              this.status = 0;
              // this.returns()
            } else {
              this.$message.error(response.data.msg);
            }
          }
        })
        .catch((e) => { });
    },
    onBljg (data) {
      // 办理结果 变化事件
      this.texts = this.operResults[this.radios].resultName;
      this.nextUser(this.operResults[this.radios].taskResultId);
    },
    nextUser (taskResultId) {
      // 下一步 办理人
      const config = {
        headers: { Authorization: dbl.get("token") },
      };
      var thta = this;
      axios
        .get("/api/flowbusimain/getTaskResultUserId/" + taskResultId, config)
        .then((response) => {
          let k = response.data.data;
          for (var i = 0; i < k.length; i++) {
            if (i == 0) {
              this.UserId = k[i].assigneeId + "SPLIT" + k[i].assignee;
            } else {
              this.UserId += k[i].assigneeId + "SPLIT" + k[i].assignee;
            }
            this.nextResultName = k[i].assignee;
          }
          if (k.length == 0) {
            this.nextResultName = "无";
            this.UserId = "";
          }
        })
        .catch((e) => { });
    },
    Opinions () {
      // 常用意见
      this.$refs.busimainOpinions.show();
    },
    returns () {
      // 返回
      //this.$refs.historyRoutes.closeTab("current");
      this.$router.push({
        path: "daiban-list",
      });
      // this.$refs.historyRoutes.delTab('/wy-flow/daiban-list2')
    },
    getList (data) {
      var thta = this;
      const config = {
        // 获取请假信息
        headers: { Authorization: dbl.get("token") },
      };

      // 预算申请业务逻辑
      getBudgetApply(data)
        .then((respData) => {
          if (respData.data.data == null) {
            this.returns();
          }

          this.form.applyData = respData.data.data;

          this.fileId = this.form.applyData.fileId;
          this.fileId2 = this.form.applyData.fileId2;
          this.showUpload = true;

          this.initItem2(this.form.applyData.applyId);

          // this.busId = this.form.applyData.fileId;
          // if (this.busId) {
          //   this.isEdit = false;
          //   this.busId = respData.data.data.fileId;
          //   this.$refs.myApply.getFiles(this.busId);
          // } else {
          // }
        })
        .catch((e) => { });

      // 获取办理 流程
      axios
        .get("/api/flowbusimain/getOperProcList/" + data, config)
        .then((response) => {
          this.busifoData = response.data.data;
        })
        .catch((e) => { });

      // 获取办理 结果
      axios
        .get("/api/flowbusimain/getTaskResultByTaskCode/" + data, config)
        .then((response) => {
          this.operResults = response.data.data;
          this.texts = this.operResults[this.radios].resultName;
          this.nextUser(this.operResults[this.radios].taskResultId);
        })
        .catch((e) => { });
    },

    // 科目
    initItem () {
      getItem(this.form.applyData.applyId).then((rep) => {
        let rspD = rep.data.data;
        if (rspD) {
          rspD = rspD.map((rs, index) => {
            rs["sortNum"] = index + 1;
            return rs;
          });
        }
        this.form.itemValueList = rspD;
      });
    },

    initItem2 () {
      getItem2(this.form.applyData.applyId).then((rep) => {
        let rspD = rep.data.data;
        rspD && (this.form.itemValueList = rspD.map((item, index) => {
          return { ...item, isNead: '1', sortNum: index + 1, children: item.children ? item.children.map(it => ({ ...it, isNead: '1' })) : item.children }
        }))
      });
    },



    success_message (msg) {
      this.$message({
        type: "success",
        message: msg,
      });
    },

    errormessage (msg) {
      this.$message({
        type: "error",
        message: msg,
      });
    },

    // 上传成功监听
    handleCompleted (data) {
      this.sendFormData(data)
    },

    onSuccess (rep, file, fileList) {
      //文件上传成功，开始保存表单
      if (rep.data != null) {
        this.sendFormData(rep.data);
      } else {
        this.err("提交失败");
      }
    },

    onError (err, file, fileList) {
      this.err("提交失败");
    },

    beforeUpload () {
      //this.loadAction("请稍等...");
    },

    // 下载
    handleClean (file) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delFiles(file.fileId, this.modelType).then((resp) => {
            if (resp.data.code === 0) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });

              this.fileList = this.fileList.filter(
                (file) => file.fileId != fileId
              );
            } else {
              this.$message({
                type: "error",
                message: "删除失败!",
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
};

Date.prototype.Format = function (fmt) {
  var o = {
    "M+": this.getMonth() + 1, //月份
    "d+": this.getDate(), //日
    "h+": this.getHours(), //小时
    "m+": this.getMinutes(), //分
    "s+": this.getSeconds(), //秒
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    S: this.getMilliseconds(), //毫秒
  };
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(
      RegExp.$1,
      (this.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt))
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
      );
  return fmt;
};
export function formatTimeToStr (times) {
  var d = new Date(times).Format("yyyy-MM-dd hh:mm:ss");
  return d.toLocaleString();
}
</script>

<style lang="scss" scoped>
.taskHandle {
  h3 {
    margin-top: 20px;
    padding-top: 15px;
    &:first-child {
      margin-top: 0;
    }
  }
  /deep/ .el-divider {
    margin-top: 14px;
  }
  .operaList {
    margin-top: 30px;
    padding-bottom: 20px;

    text-align: center;
  }
}
.custom-tree-node {
  font-size: 14px;

  display: flex;
  align-items: center;
  flex: 1;
  justify-content: space-between;

  padding-right: 8px;
}

.card-box {
  .card-title {
    margin-bottom: 20px;
  }
}
//表头结算样式
.header {
  height: 74px;
  text-align: center;
  margin: 0 auto;
  width: 99%;
  /* max-width: 99%; */

  .subject {
    font-size: 14px;
    width: 25%;
    height: 74px;
    line-height: 74px;
    text-align: left;
    border: 1px solid #ebeef5;

    font-weight: normal;
    padding-left: 20px;
    float: left;
  }

  .aggregate {
    height: 74px;
    float: right;
    width: 75%;

    .aggregatebox {
      height: 50%;
      width: 100%;

      .etui {
        font-size: 14px;
        border: 1px solid #ebeef5;
        width: 33.33%;
        height: 100%;
        line-height: 36px;
        text-align: center;
        font-weight: normal;
        float: left;
      }

      .etui /deep/ .el-form-item__content {
        margin-left: 0 !important;
      }

      // background-color: yellow;
    }
  }
}

// 树形结构修改默认样式
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  font-weight: normal;
  justify-content: space-between;
  /* font-size: 14px; */
  font-size: 14px;
  padding-right: 8px;
}

.box /deep/.el-tree-node__content {
  height: 53px;
}

// 修改开关组件
.box /deep/.el-switch__core {
  height: 14px;
}

//修改开关组件原型开关
.box /deep/.el-switch__core::after {
  height: 12px;
  width: 12px;
  margin-left: 0px;
  top: 0;
}

// 修改开关组件切换后样式
.box /deep/ .el-switch.is-checked .el-switch__core::after {
  margin-left: -14px;
  top: 0;
}

//
.inputbox {
  text-align: center;
}

//修改树形组件 输入框样式
.inputbox /deep/ .el-input__inner {
  height: 25px;
  width: 50%;
}

.footer /deep/.el-button {
  float: right;
  margin-right: 5px;
}
</style>
